package com.study.notepad.filter;/*
 @Author Cedar
 @DESCRIPTION 
*/

import com.study.notepad.bean.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException,
            ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        String contextPath = request.getContextPath();

        String[] notFilterUris = new String[]{"/login.jsp", "/user/login", "/register.jsp", "/user/register",
                "/404.jsp","/forward.jsp"};
        for (String uri : notFilterUris) {
            if (requestURI.equals(contextPath+uri)) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("loginUser");
        if (user == null ) {
            response.sendRedirect(contextPath +"/login.jsp");
            return;
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
